package com.jl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpHost;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.*;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * es sql查询工具
 */
public class JLEsSearchSql {

    /**
     * 连接es
     */
    public static void connect(String ip, int port) {
        HttpHost[] httpHosts = new HttpHost[1];
        httpHosts[0] = new HttpHost(ip, port);
        RestClientBuilder builder = RestClient.builder(httpHosts);
        RestClient restClient = RestClient.builder(httpHosts).build();
        while (true) {
            Scanner sc = new Scanner(System.in);
            System.out.print("sql： ");
            String sql = sc.nextLine();
            if (!StringUtils.isEmpty(sql)) {
                sqlExec(restClient, builder, sql);
            }
        }
    }

    private static void sqlExec(RestClient restClient, RestClientBuilder builder, String sql) {
        String way = sql.substring(0, 4);
        if (way.toLowerCase().equals("drop")) {
            drop(builder, sql);
        } else {
            query(restClient, sql);
        }
    }

    public static void drop(RestClientBuilder builder, String sql) {
        String indexName = sql.substring(sql.lastIndexOf(" ") + 1);
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        try {
            AcknowledgedResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);
            boolean acknowledged = deleteIndexResponse.isAcknowledged();
            if (acknowledged) {
                System.out.println("\n\n删除成功\n\n");
            } else {
                System.out.println("\n\n删除失败\n\n");
            }
        } catch (Exception e) {
            System.out.println("\n\nsql或连接错误\n\n");
        }
    }

    public static void query(RestClient restClient, String sql) {
        List<Map<String, Object>> list = new ArrayList();
        try {
            Request request = new Request("GET", "/_sql");
            request.addParameter("format", "json");
            request.setJsonEntity("{\"query\":\"" + sql + "\"}");
            Response response = restClient.performRequest(request);
            String text = EntityUtils.toString(response.getEntity());

            JSONObject json = JSONUtil.parseObj(text);
            JSONArray columnsJsonArray = json.getJSONArray("columns");
            JSONArray rowsJsonArray = json.getJSONArray("rows");

            String[] columns = new String[columnsJsonArray.size()];
            for (int i = 0; i < columnsJsonArray.size(); ++i) {
                JSONObject columnJsonObject = JSONUtil.parseObj(columnsJsonArray.get(i));
                columns[i] = columnJsonObject.getStr("name");
            }

            for (int i = 0; i < rowsJsonArray.size(); i++) {
                JSONArray row = JSONUtil.parseArray(rowsJsonArray.get(i));
                Map<String, Object> map = new HashMap();
                for (int j = 0; j < row.size(); ++j) {
                    Object obj = row.get(j);
                    map.put(columns[j], obj);
                }
                list.add(map);
            }
        } catch (Exception e) {
            System.out.println("\n\nsql或连接错误\n\n");
        }
        if (list.size() > 0) {
            System.out.println("\n");
        }
        for (Map<String, Object> map : list) {
            System.out.println(map);
        }
        if (list.size() > 0) {
            System.out.println("\n");
        }
    }
}
